package com.peanuts.tender.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 所有controller继承此类
 * Created by wangke on 2017/2/24.
 */
public class BaseController {

    Logger log = Logger.getLogger(BaseController.class);
    public void writeClientJson(HttpServletResponse response, Object obj, String callback) {
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            StringBuilder resultJson = new StringBuilder("");
            if(callback != null && !"".equals(callback)) {
                resultJson.append(callback).append('(').append(JSONObject.toJSON(obj).toString()).append(')');
            } else {
                resultJson.append(JSONObject.toJSON(obj).toString());
            }
            pw.write(resultJson.toString());
        } catch (IOException e) {
            log.error("返回客户端json出错:"+ JSONObject.toJSON(obj).toString(),e);
        } finally {
            if (null != pw) {
                pw.flush();
                pw.close();
            }
        }
    }

    public void writeClientText(HttpServletResponse response, String res,
                                String callback) {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            StringBuilder result = new StringBuilder("");
            if(callback != null && !"".equals(callback)) {
                result.append(callback).append('(').append(res).append(')');
            } else {
                result.append(res);
            }
            pw.write(result.toString());
        } catch (IOException e) {
            log.error("返回客户端text出错:"+res,e);
        } finally {
            if (null != pw) {
                pw.flush();
                pw.close();
            }
        }
    }
    /**
     * 得到request对象
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }


}
